package middleware

import (
	"github.com/gin-gonic/gin"
	"net/http"
)

func CorsHandler() gin.HandlerFunc {
	return func(context *gin.Context) {
		//withCredentials = true 表示允许跨域携带cookie信息
		//前端设置了 withCredentials = true ，那么后端必须要设置 Access-Control-Allow-Origin为你的源地址，而不能设置为 “*”
		context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
		//context.Writer.Header().Set("Access-Control-Allow-Origin", context.GetHeader("Origin"))

		context.Writer.Header().Set("Access-Control-Allow-Credentials", "true")
		context.Writer.Header().Set("Access-Control-Allow-Methods", "*")
		context.Writer.Header().Set("Access-Control-Allow-Headers", "*")
		context.Writer.Header().Set("Access-Control-Max-Age", "86400") // todo 缓存时间

		if context.Request.Method == http.MethodOptions {
			context.AbortWithStatus(http.StatusBadRequest)
		} else {
			context.Next()
		}
	}
}
